package happy.robot;
import happy.robot.constant.CustomerConstants;
import happy.robot.entity.Customer;
import happy.robot.mapper.CustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class ListController implements Controller {


    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        int customerCount = customerMapper.selectCustomerCount();
        int targetPage = Integer.parseInt(req.getParameter("targetPage") != null ? req.getParameter("targetPage") : "1");
        List<Customer> list = customerMapper.selectCustomers((targetPage - 1) * CustomerConstants.PAGE_SIZE, CustomerConstants.PAGE_SIZE);
        ModelAndView mv = new ModelAndView();
        mv.addObject("list", list);
        mv.addObject("currentPage", targetPage);
        mv.addObject("pageCount", customerCount / CustomerConstants.PAGE_SIZE + (customerCount % CustomerConstants.PAGE_SIZE == 0 ? 0 : 1));
        mv.setViewName("list");
        return mv;
    }
}